<?php
/**
 * Created by JetBrains PhpStorm.
 * User: User
 * Date: 31.10.12
 * Time: 13:50
 * To change this template use File | Settings | File Templates.
 */

function smarty_modifier_translate_composite_payment_name($string, $domain = null, $mode = null)
{
	if (empty($string)) {
		return $string;
	}
	
	$i18n  = SJB_I18N::getInstance();
	
	$prefixProducts    = 'Payment for product(s)';
	$isProductsPayment = preg_match("#Payment for product\(s\) (.+)#", $string, $matchesProducts);

	if ($isProductsPayment) {
		$products = $matchesProducts[1];
		if (strpos($products, ',') !== false) {
			$products = explode(',', $products);
		} else {
			$products = array( trim($products) );
		}

		// translate every productName
		$translatedProductNames   = array();
		foreach ($products as $productName) {
			$value = trim($productName);
			array_push($translatedProductNames, $i18n->gettext($domain, $value, $mode));
		}
		$translatedProductNames = implode(', ', $translatedProductNames);
		$prefix = $i18n->gettext($domain, trim($prefixProducts), $mode);
		$string = $prefix . ' '. $translatedProductNames;
	} else {
		$isFeaturedPayment = preg_match("#(Payment for )?upgrade listing ID (\d+) to featured#", $string, $matchesFeatured);
		$isPriorityPayment = preg_match("#(Payment for )?upgrade listing ID (\d+) to priority#", $string, $matchesPriority);
		$matches = '';
		if ($isFeaturedPayment) {
			$matches = $matchesFeatured;
			$prefix  = 'Payment for upgrade listing ID $listingId to featured';
		} elseif ($isPriorityPayment) {
			$matches = $matchesPriority;
			$prefix  = 'Payment for upgrade listing ID $listingId to priority';
		}

		if ($matches) {
			if (empty($matches[1])) {
				$prefix = str_replace('Payment for ', '', $prefix);
			}
			$listingId = $matches[2];
			$prefix    = $i18n->gettext($domain, trim($prefix), $mode);
			$string    = str_replace('{$listingId}', $listingId, $prefix);
		}
	}
	return $string;
}